<template>
  <div class="health-data">
    
    <el-card class="health-card">
      <template #header>
        <div class="card-header">
          <h2>体检数据趋势</h2>
          
        </div>
      </template>
      <div v-if="hasRecords && !isDataLoading" class="health-content">
        <div class="charts-section">
          <el-row :gutter="24">
            <el-col :span="12">
              <div class="chart-wrapper">
                <div ref="bloodPressureChart" class="chart-container"></div>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="chart-wrapper">
                <div ref="bloodSugarChart" class="chart-container"></div>
              </div>
            </el-col>
          </el-row>
        </div>
        
        <div class="table-section">
          <div class="table-header">
            <h3>详细记录</h3> 
          </div>
         
          <el-table 
            :data="healthRecords" 
            style="width: 100%; height: 500px;overflow-y: auto;"
            :header-cell-style="{ background: '#fafafa', color: '#333', fontWeight: '600' }"
            stripe
          >
            <el-table-column prop="date" label="日期" width="120" sortable />
            <el-table-column label="血压" width="120">
              <template #default="{ row }">
                <span class="blood-pressure">
                  {{ row.systolic }}/{{ row.diastolic }}
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="bloodSugar" label="血糖" width="100">
              <template #default="{ row }">
                <span class="blood-sugar">{{ row.bloodSugar }} mmol/L</span>
              </template>
            </el-table-column>
            <el-table-column prop="weight" label="体重" width="100">
              <template #default="{ row }">
                <span>{{ row.weight }} kg</span>
              </template>
            </el-table-column>
            <el-table-column prop="temperature" label="体温" width="100">
              <template #default="{ row }">
                <span>{{ row.temperature }} °C</span>
              </template>
            </el-table-column>
            <el-table-column prop="heartRate" label="心率" width="100">
              <template #default="{ row }">
                <span>{{ row.heartRate }} bpm</span>
              </template>
            </el-table-column>
            <el-table-column prop="notes" label="备注" show-overflow-tooltip />
            <el-table-column label="操作" width="120" fixed="right">
              <template #default="{ row }">
                <el-button type="primary" size="small" @click="editRecord(row)" >编辑</el-button>
                <el-button type="danger" size="small" @click="deleteMedication(row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="pagination-wrapper">
              <el-pagination
                v-model:current-page="currentPage"
                v-model:page-size="pageSize"
                :page-sizes="[10, 20, 50, 100]"
                :total="totalRecords"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />
            </div>

          <el-dialog v-model="showHealthRecordDialog" title="更改健康记录" width="500px">
         <el-form ref="healthRecordFormRef" :model="healthRecordForm" :rules="healthRecordRule" label-width="100px">
         <el-form-item label="日期" prop="date">
          <el-date-picker
            v-model="healthRecordForm.date"
            type="date"
            placeholder="选择日期"
            style="width: 100%"
          />
        </el-form-item>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="收缩压" prop="systolic">
              <el-input-number
                v-model="healthRecordForm.systolic"
                :min="0"
                :max="300"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="舒张压" prop="diastolic">
              <el-input-number
                v-model="healthRecordForm.diastolic"
                :min="0"
                :max="200"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="血糖" prop="bloodSugar">
              <el-input-number
                v-model="healthRecordForm.bloodSugar"
                :min="0"
                :max="50"
                :precision="1"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="体重(kg)" prop="weight">
              <el-input-number
                v-model="healthRecordForm.weight"
                :min="0"
                :max="200"
                :precision="1"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="体温(°C)" prop="temperature">
              <el-input-number
                v-model="healthRecordForm.temperature"
                :min="30"
                :max="45"
                :precision="1"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="心率" prop="heartRate">
              <el-input-number
                v-model="healthRecordForm.heartRate"
                :min="0"
                :max="300"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注" prop="notes">
          <el-input
            v-model="healthRecordForm.notes"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="showHealthRecordDialog = false">取消</el-button>
        <el-button type="primary" @click="setHealthRecord">保存</el-button>
      </template>
    </el-dialog>
        
        
        </div>
      </div>
      <div v-else class="no-data-container">
        <div v-if="isDataLoading">
          <el-spin tip="加载中..." />
        </div>
        <div v-else-if="errorMessage" class="error-message">
          <el-alert
            title="数据加载失败"
            type="error"
            :description="errorMessage"
            show-icon
          />
          <el-button @click="getHealthRecords" type="primary" style="margin-top: 16px">重试</el-button>
        </div>
        <div v-else>
          <el-empty description="暂无体检数据" :image-size="200" />
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, nextTick, onBeforeUnmount, watch ,reactive} from 'vue'
import * as echarts from 'echarts'
import { useUserStore } from '@/stores/user'
import { useElderlyStore } from '@/stores/elderly'
import {getALLCheckupDataById,deleteCheckupData,updateCheckupData} from '@/api/health_checkup_dateinfo/health_checkup_datainfo'
import { ElMessage, ElMessageBox } from 'element-plus'


//初始化使用getHealthRecords()获取数据




const userStore = useUserStore()
const elderlyStore = useElderlyStore()
const elderlyId = ref(localStorage.getItem('elderlyId') || '')
const searchKeyword = ref('')
const healthRecordFormRef = ref([])
const showHealthRecordDialog = ref(false)
const currentPage = ref(1); // 当前页码
const pageSize = ref(10); // 每页显示条数
const totalRecords = ref(0); // 总记录数

const elderly = computed(() => {
  if (!userStore.currentUser) return null
  return elderlyStore.elderlyList.find(e => e.id === userStore.currentUser?.id) || null
})
//分页方法
const handleSizeChange = (size: number) => {
  pageSize.value = size;
  getHealthRecords();
};

const handleCurrentChange = (page: number) => {
  currentPage.value = page;
  getHealthRecords();
};


// 定义健康记录的类型
interface HealthRecord {
  id : string;
  date: Date;
  systolic: number;
  diastolic: number;
  bloodSugar: number;
  weight: number | null;
  temperature: number | null;
  heartRate: number | null;
  notes: string | null;
}

const healthRecordForm = reactive<HealthRecord>({
  id: '',
  date: new Date(),
  systolic: 0,
  diastolic: 0,
  bloodSugar: 0,
  weight: 0,
  temperature: 0,
  heartRate: 0,
  notes: ''

})

// 扩展API响应类型定义
interface APIResponse {
  success: boolean;
  message?: string;
  data?: HealthRecord[];
}


// 健康记录相关响应式数据
const healthRecords = ref<HealthRecord[]>([])
//从apihealth_checkup_dateinfo.js获取健康记录数据
const getHealthRecords = async () => {
  try {
    const id = elderlyId.value;
    if (!id) return;
    const response = await getALLCheckupDataById(id); // 调用 API
    if (response.code === 200) {
      // 分页显示数据
      healthRecords.value = response.data
        .map(record => ({ ...record, date: new Date(record.date) }))
        .slice((currentPage.value - 1) * pageSize.value, currentPage.value * pageSize.value);
      // 更新总记录数
      totalRecords.value = response.data.length;
    }
  } catch (error) {
    console.log('获取健康记录失败');
  }
};
//删除健康记录
const deleteMedication = async (record: HealthRecord) => {
  try {
    await ElMessageBox.confirm('确定要删除这条用药记录吗？', '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 这里应该调用API删除记录
    await deleteCheckupData(record.id);
    ElMessage.success('删除成功')
  } catch {
    // 用户取消

  }
  initCharts()
  getHealthRecords()
}


const isLoading = ref<boolean>(false)
const error = ref<string | null>(null)

// 暴露计算属性给模板使用
const isDataLoading = computed(() => {
  return isLoading.value
})

const errorMessage = computed(() => {
  return error.value
})

const hasRecords = computed(() => {
  return healthRecords.value.length > 0
})

// 从API获取健康记录


const bloodPressureChart = ref()
const bloodSugarChart = ref()

// 健康记录规则
const healthRecordRule = {
  date: [{ required: false, message: '请选择日期', trigger: 'change' }],
  systolic: [{ required: false, message: '请输入收缩压', trigger: 'blur' }],
  diastolic: [{ required: false, message: '请输入舒张压', trigger: 'blur' }],
  bloodSugar: [{ required: false, message: '请输入血糖', trigger: 'blur' }],
  weight: [{ required: false, message: '请输入体重', trigger: 'blur' }],
  height: [{ required: false, message: '请输入身高', trigger: 'blur' }],
  temperature: [{ required: false, message: '请输入体温', trigger: 'blur' }],
  heartRate: [{ required: false, message: '请输入心率', trigger: 'blur' }],
  notes: [{ required: false, message: '请输入备注', trigger: 'blur' }]
}

//
const setHealthRecord = async () => { 
  if(!healthRecordFormRef.value)  return

  try {
    
    
    const record = {
      ...healthRecordForm,
      id: healthRecordForm.id,
      elderlyId: elderlyId.value,
      date: new Date(healthRecordForm.date).toISOString()
    }
    
    ElMessage.success('健康记录更改成功')
    showHealthRecordDialog.value = false
    await updateCheckupData(healthRecordForm.id, record)
  }
  catch (error) {
    console.error('保存失败:', error)
  }
initCharts()
getHealthRecords()

}

const editRecord = (row: HealthRecord) => {
  console.log('编辑记录:', row)
  Object.assign(healthRecordForm, row) // 将 row 数据复制到 healthRecordForm，包括 id
  showHealthRecordDialog.value = true
}
const initCharts = () => {
  nextTick(() => {
    if (bloodPressureChart.value && bloodSugarChart.value && healthRecords.value.length) {
      // 血压图表
      const bpChart = echarts.init(bloodPressureChart.value)
      const bpData = healthRecords.value.map(record => ({
        date: new Date(record.date).toLocaleDateString(),
        systolic: record.systolic,
        diastolic: record.diastolic
      }))
      
      bpChart.setOption({
        title: { text: '血压趋势', left: 'center' },
        tooltip: { trigger: 'axis' },
        legend: { data: ['收缩压', '舒张压'], top: 30 },
        grid: { top: 80, left: 60, right: 40, bottom: 60 },
        xAxis: { type: 'category', data: bpData.map(item => item.date), axisLabel: { rotate: 45 } },
        yAxis: { type: 'value', name: 'mmHg' },
        series: [
          {
            name: '收缩压',
            type: 'line',
            data: bpData.map(item => item.systolic),
            smooth: true,
            lineStyle: { width: 3 },
            itemStyle: { color: '#ff6b6b' }
          },
          {
            name: '舒张压',
            type: 'line',
            data: bpData.map(item => item.diastolic),
            smooth: true,
            lineStyle: { width: 3 },
            itemStyle: { color: '#4ecdc4' }
          }
        ]
      })
      
      // 血糖图表
      const bsChart = echarts.init(bloodSugarChart.value)
      const bsData = healthRecords.value.map(record => ({
        date: new Date(record.date).toLocaleDateString(),
        value: record.bloodSugar
      }))
      
      bsChart.setOption({
        title: { text: '血糖趋势', left: 'center' },
        tooltip: { trigger: 'axis' },
        grid: { top: 80, left: 60, right: 40, bottom: 60 },
        xAxis: { type: 'category', data: bsData.map(item => item.date), axisLabel: { rotate: 45 } },
        yAxis: { type: 'value', name: 'mmol/L' },
        series: [
          {
            name: '血糖',
            type: 'line',
            data: bsData.map(item => item.value),
            smooth: true,
            lineStyle: { width: 3 },
            itemStyle: { color: '#45b7d1' },
            areaStyle: {
              color: {
                type: 'linear', x: 0, y: 0, x2: 0, y2: 1,
                colorStops: [
                  { offset: 0, color: 'rgba(69, 183, 209, 0.3)' },
                  { offset: 1, color: 'rgba(69, 183, 209, 0.1)' }
                ]
              }
            }
          }
        ]
      })
      
      // 响应式处理
      window.addEventListener('resize', () => {
        bpChart.resize()
        bsChart.resize()
      })
    }
  })
}



// 定时刷新
let refreshInterval: number | null = null

// 在onMounted中初始化图表
onMounted(async () => {
  console.log('HealthData 组件已挂载');
  console.log('elderlyId:', elderlyId.value);

  currentPage.value = 1; // 初始化当前页码
  pageSize.value = 10; // 初始化每页显示条数
  await getHealthRecords(); // 获取分页数据
  initCharts();

  // 每5分钟自动刷新数据
  refreshInterval = window.setInterval(getHealthRecords, 5 * 60 * 1000);
});

// 组件卸载时清除定时器
onBeforeUnmount(() => {
  if (refreshInterval !== null) {
    clearInterval(refreshInterval)
  }
})

// 监听healthRecords变化并更新图表
watch(
  () => healthRecords.value,
  () => {
    initCharts();
    // 更新总记录数
    totalRecords.value = healthRecords.value.length;
  },
  { immediate: true, deep: true }
);

// 暴露计算属性给模板使用
defineExpose({
  healthRecords,
  isDataLoading,
  errorMessage,
  hasRecords
})
</script>

<style scoped>
.health-data {
  height: 100vh; /* 设置页面高度为视口高度 */
  width: 100%;
  overflow-y: auto; /* 添加滚动条 */
  padding: 20px; /* 可选：添加内边距 */
  box-sizing: border-box; /* 确保内边距不会影响页面高度 */
}

.health-card {
  height: 130%;
  display: flex;
  flex-direction: column;
}

.health-card :deep(.el-card__body) {
  flex: 1;
  padding: 0;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h2 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: #333;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.health-content {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.charts-section {
  padding: 24px;
  background: #fafafa;
  border-bottom: 1px solid #e6e6e6;
}

.chart-wrapper {
  background: white;
  border-radius: 8px;
  padding: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.chart-container {
  height: 350px;
  width: 100%;
}

.table-section {
  flex: 1;
  padding: 24px;
  
  overflow-y: auto;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.table-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.blood-pressure {
  font-weight: 500;
  color: #409eff;
}

.blood-sugar {
  font-weight: 500;
  color: #67c23a;
}

.no-data-container {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  padding: 40px;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .charts-section {
    padding: 20px;
  }
  
  .table-section {
    padding: 20px;
  }
  
  .chart-container {
    height: 300px;
  }
}

@media (max-width: 768px) {
  .charts-section {
    padding: 16px;
  }
  
  .table-section {
    padding: 16px;
  }
  
  .card-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
  
  .table-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
  
  .chart-container {
    height: 250px;
  }
}

.detail-records-container {
  max-height: 400px;
  overflow-y: auto;
}
.detail-records-container .el-table {
  max-height: 400px;
  overflow-y: auto;
}
.pagination-wrapper {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style> 